package com.zrrd.reggie.controller;

import com.zrrd.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("E:\\photo")
    private String baseUrl;

    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        log.info("收到文件===>{}",file.getOriginalFilename());
        log.info("文件存放位置===>{}",baseUrl);

        //获取文件原始名字
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("文件后缀名==>{}",suffix);

        //使用UUID生成一个文件名字
        String fileName = UUID.randomUUID().toString();
        //拼接出文件新名字
        fileName = fileName + suffix;

        //将文件存放的目录 封装成一个File对象
        File f = new File(baseUrl);
        //判断是否存在
        if(!f.exists()){
            //创建文件夹
            f.mkdirs();
        }
        //将文件存入到指定位置
        file.transferTo(new File(f,fileName));
        //返回给前端文件名称
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try{
            //创建字节输入流 读取指定文件内容
            FileInputStream fis = new FileInputStream(new File(baseUrl,name));
            //通过响应对象 获取输入流
            ServletOutputStream os = response.getOutputStream();
            //循环读写
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1){
                os.write(bytes,0,len);
                os.flush();
            }
            //关闭资源
            fis.close();
            os.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
